<template>
  <view class="container">
    <!-- Calendar Header -->
    <view class="calendar-header">
      <view class="month-selector">
        <u-button 
          icon="arrow-left" 
          :plain="true"
          @click="previousMonth"
        ></u-button>
        <text class="current-month">{{ currentMonthYear }}</text>
        <u-button 
          icon="arrow-right" 
          :plain="true"
          @click="nextMonth"
        ></u-button>
      </view>
      <view class="view-switcher">
        <u-button-group>
          <u-button 
            :type="viewMode === 'month' ? 'primary' : 'info'"
            :plain="viewMode !== 'month'"
            @click="viewMode = 'month'"
          >Month</u-button>
          <u-button 
            :type="viewMode === 'week' ? 'primary' : 'info'"
            :plain="viewMode !== 'week'"
            @click="viewMode = 'week'"
          >Week</u-button>
          <u-button 
            :type="viewMode === 'day' ? 'primary' : 'info'"
            :plain="viewMode !== 'day'"
            @click="viewMode = 'day'"
          >Day</u-button>
        </u-button-group>
      </view>
    </view>

    <!-- Calendar Grid -->
    <scroll-view scroll-y class="calendar-content">
      <!-- Month View -->
      <view v-if="viewMode === 'month'" class="month-view">
        <!-- Weekday Headers -->
        <view class="weekday-header">
          <text 
            v-for="day in weekDays" 
            :key="day"
            class="weekday"
          >{{ day }}</text>
        </view>

        <!-- Calendar Days -->
        <view class="days-grid">
          <view 
            v-for="(day, index) in calendarDays"
            :key="index"
            :class="['day-cell', {
              'other-month': !day.isCurrentMonth,
              'today': day.isToday,
              'has-events': day.events.length > 0
            }]"
            @click="selectDay(day)"
          >
            <text class="day-number">{{ day.date }}</text>
            <view 
              v-if="day.events.length > 0"
              class="event-indicators"
            >
              <view 
                v-for="(event, eventIndex) in day.events.slice(0, 3)"
                :key="eventIndex"
                class="event-dot"
                :style="{ backgroundColor: event.color }"
              ></view>
              <text v-if="day.events.length > 3" class="more-events">
                +{{ day.events.length - 3 }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- Week View -->
      <view v-else-if="viewMode === 'week'" class="week-view">
        <!-- Time Grid -->
        <view class="time-grid">
          <view class="time-column">
            <view 
              v-for="hour in hours"
              :key="hour"
              class="time-slot"
            >
              <text class="hour">{{ formatHour(hour) }}</text>
            </view>
          </view>
          <scroll-view 
            scroll-x 
            class="days-columns"
            :scroll-into-view="'day-' + todayIndex"
          >
            <view class="week-days">
              <view 
                v-for="(day, index) in weekDays"
                :key="index"
                :id="'day-' + index"
                class="day-column"
              >
                <text class="day-header">{{ day }}</text>
                <view 
                  v-for="hour in hours"
                  :key="hour"
                  class="hour-slot"
                >
                  <view 
                    v-for="event in getEventsForHour(day, hour)"
                    :key="event.id"
                    class="event-block"
                    :style="{
                      backgroundColor: event.color,
                      height: `${event.duration * 60}px`
                    }"
                    @click="showEventDetails(event)"
                  >
                    <text class="event-title">{{ event.title }}</text>
                    <text class="event-time">{{ formatEventTime(event) }}</text>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>

      <!-- Day View -->
      <view v-else class="day-view">
        <view class="time-slots">
          <view 
            v-for="hour in hours"
            :key="hour"
            class="time-slot"
          >
            <text class="hour">{{ formatHour(hour) }}</text>
            <view class="hour-content">
              <view 
                v-for="event in getEventsForHour('', hour)"
                :key="event.id"
                class="event-block"
                :style="{
                  backgroundColor: event.color,
                  height: `${event.duration * 60}px`
                }"
                @click="showEventDetails(event)"
              >
                <text class="event-title">{{ event.title }}</text>
                <text class="event-location" v-if="event.location">
                  {{ event.location }}
                </text>
                <text class="event-time">{{ formatEventTime(event) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- Add Event FAB -->
    <view class="fab-button">
      <u-button 
        type="primary" 
        icon="plus" 
        shape="circle"
        @click="showAddEvent"
      ></u-button>
    </view>

    <!-- Event Details Modal -->
    <u-popup
      v-model="showEventModal"
      mode="center"
      borderRadius="12"
    >
      <view class="event-modal">
        <view class="modal-header">
          <text class="modal-title">{{ selectedEvent?.title }}</text>
          <u-icon name="close" @click="showEventModal = false"></u-icon>
        </view>
        <view class="modal-content">
          <view class="event-detail">
            <u-icon name="calendar" size="28" color="#666"></u-icon>
            <text>{{ formatEventDateTime(selectedEvent) }}</text>
          </view>
          <view class="event-detail" v-if="selectedEvent?.location">
            <u-icon name="map-marker" size="28" color="#666"></u-icon>
            <text>{{ selectedEvent.location }}</text>
          </view>
          <view class="event-detail" v-if="selectedEvent?.description">
            <u-icon name="file-text" size="28" color="#666"></u-icon>
            <text>{{ selectedEvent.description }}</text>
          </view>
        </view>
        <view class="modal-actions">
          <u-button 
            :plain="true"
            icon="edit"
            @click="editEvent"
          >Edit</u-button>
          <u-button 
            type="error"
            :plain="true"
            icon="trash"
            @click="deleteEvent"
          >Delete</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      viewMode: 'month',
      currentDate: new Date(),
      showEventModal: false,
      selectedEvent: null,
      weekDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      hours: Array.from({ length: 24 }, (_, i) => i),
      events: [
        {
          id: 1,
          title: 'Anatomy Lecture',
          date: '2024-03-20',
          startTime: '09:00',
          duration: 2, // hours
          location: 'Room 301',
          description: 'Introduction to cardiovascular system',
          color: '#4b7bec'
        },
        {
          id: 2,
          title: 'Lab Session',
          date: '2024-03-20',
          startTime: '14:00',
          duration: 3,
          location: 'Lab B',
          description: 'Practical examination of heart specimens',
          color: '#2ed573'
        }
      ]
    }
  },
  computed: {
    currentMonthYear() {
      return this.currentDate.toLocaleDateString('en-US', {
        month: 'long',
        year: 'numeric'
      })
    },
    calendarDays() {
      const year = this.currentDate.getFullYear()
      const month = this.currentDate.getMonth()
      const firstDay = new Date(year, month, 1)
      const lastDay = new Date(year, month + 1, 0)
      const days = []
      
      // Add days from previous month
      const firstDayOfWeek = firstDay.getDay()
      for (let i = firstDayOfWeek - 1; i >= 0; i--) {
        const date = new Date(year, month, -i)
        days.push({
          date: date.getDate(),
          isCurrentMonth: false,
          isToday: this.isToday(date),
          events: this.getEventsForDate(date)
        })
      }
      
      // Add days of current month
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month, i)
        days.push({
          date: i,
          isCurrentMonth: true,
          isToday: this.isToday(date),
          events: this.getEventsForDate(date)
        })
      }
      
      // Add days from next month
      const remainingDays = 42 - days.length // 6 weeks * 7 days
      for (let i = 1; i <= remainingDays; i++) {
        const date = new Date(year, month + 1, i)
        days.push({
          date: i,
          isCurrentMonth: false,
          isToday: this.isToday(date),
          events: this.getEventsForDate(date)
        })
      }
      
      return days
    },
    todayIndex() {
      return new Date().getDay()
    }
  },
  methods: {
    previousMonth() {
      this.currentDate = new Date(
        this.currentDate.getFullYear(),
        this.currentDate.getMonth() - 1,
        1
      )
    },
    nextMonth() {
      this.currentDate = new Date(
        this.currentDate.getFullYear(),
        this.currentDate.getMonth() + 1,
        1
      )
    },
    isToday(date) {
      const today = new Date()
      return date.toDateString() === today.toDateString()
    },
    formatHour(hour) {
      return `${hour.toString().padStart(2, '0')}:00`
    },
    formatEventTime(event) {
      const [hours, minutes] = event.startTime.split(':')
      const startTime = `${hours}:${minutes}`
      const endHour = (parseInt(hours) + event.duration)
      const endTime = `${endHour.toString().padStart(2, '0')}:${minutes}`
      return `${startTime} - ${endTime}`
    },
    formatEventDateTime(event) {
      if (!event) return ''
      const date = new Date(event.date)
      return `${date.toLocaleDateString('en-US', {
        weekday: 'long',
        month: 'long',
        day: 'numeric'
      })} ${this.formatEventTime(event)}`
    },
    getEventsForDate(date) {
      return this.events.filter(event => 
        new Date(event.date).toDateString() === date.toDateString()
      )
    },
    getEventsForHour(day, hour) {
      return this.events.filter(event => {
        const eventHour = parseInt(event.startTime.split(':')[0])
        return eventHour === hour
      })
    },
    selectDay(day) {
      if (day.events.length > 0) {
        this.viewMode = 'day'
        this.currentDate = new Date(
          this.currentDate.getFullYear(),
          this.currentDate.getMonth(),
          day.date
        )
      }
    },
    showEventDetails(event) {
      this.selectedEvent = event
      this.showEventModal = true
    },
    showAddEvent() {
      uni.navigateTo({
        url: '/pages/more/calendar-event'
      })
    },
    editEvent() {
      this.showEventModal = false
      uni.navigateTo({
        url: `/pages/more/calendar-event?id=${this.selectedEvent.id}`
      })
    },
    deleteEvent() {
      uni.showModal({
        title: 'Delete Event',
        content: 'Are you sure you want to delete this event?',
        success: (res) => {
          if (res.confirm) {
            // TODO: Implement event deletion
            this.events = this.events.filter(e => e.id !== this.selectedEvent.id)
            this.showEventModal = false
            uni.showToast({
              title: 'Event deleted',
              icon: 'success'
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.calendar-header {
  background-color: #ffffff;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .month-selector {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;

    .current-month {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .view-switcher {
    display: flex;
    justify-content: center;
  }
}

.calendar-content {
  flex: 1;
  padding: 30rpx;
}

.month-view {
  .weekday-header {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    margin-bottom: 20rpx;

    .weekday {
      text-align: center;
      font-size: 26rpx;
      color: #666;
      padding: 10rpx;
    }
  }

  .days-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 2rpx;
    background-color: #eee;
    border: 2rpx solid #eee;
    border-radius: 12rpx;
    overflow: hidden;

    .day-cell {
      background-color: #ffffff;
      min-height: 120rpx;
      padding: 10rpx;
      position: relative;

      &.other-month {
        background-color: #f8f9fa;

        .day-number {
          color: #999;
        }
      }

      &.today {
        .day-number {
          background-color: #4b7bec;
          color: #ffffff;
        }
      }

      .day-number {
        display: inline-block;
        width: 50rpx;
        height: 50rpx;
        line-height: 50rpx;
        text-align: center;
        border-radius: 25rpx;
        font-size: 26rpx;
        color: #333;
      }

      .event-indicators {
        display: flex;
        flex-wrap: wrap;
        gap: 6rpx;
        margin-top: 10rpx;

        .event-dot {
          width: 12rpx;
          height: 12rpx;
          border-radius: 6rpx;
        }

        .more-events {
          font-size: 20rpx;
          color: #666;
        }
      }
    }
  }
}

.week-view, .day-view {
  .time-grid {
    display: flex;

    .time-column {
      width: 100rpx;
      flex-shrink: 0;
    }

    .days-columns {
      flex: 1;
      overflow-x: auto;

      .week-days {
        display: flex;
        min-width: fit-content;

        .day-column {
          width: 200rpx;
          border-left: 2rpx solid #eee;

          .day-header {
            text-align: center;
            padding: 20rpx;
            font-size: 26rpx;
            color: #666;
            background-color: #f8f9fa;
          }
        }
      }
    }
  }

  .time-slot {
    height: 60px;
    border-bottom: 2rpx solid #eee;
    position: relative;

    .hour {
      font-size: 24rpx;
      color: #999;
      padding: 10rpx;
    }

    .hour-content {
      position: relative;
    }
  }

  .event-block {
    position: absolute;
    left: 10rpx;
    right: 10rpx;
    padding: 10rpx;
    border-radius: 8rpx;
    overflow: hidden;
    z-index: 1;

    .event-title {
      font-size: 24rpx;
      color: #ffffff;
      font-weight: bold;
      margin-bottom: 4rpx;
    }

    .event-location, .event-time {
      font-size: 20rpx;
      color: rgba(255, 255, 255, 0.9);
    }
  }
}

.fab-button {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
}

.event-modal {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;

  .modal-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2rpx solid #eee;

    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .modal-content {
    padding: 30rpx;

    .event-detail {
      display: flex;
      align-items: flex-start;
      gap: 16rpx;
      margin-bottom: 20rpx;

      text {
        font-size: 28rpx;
        color: #666;
        flex: 1;
      }
    }
  }

  .modal-actions {
    padding: 30rpx;
    display: flex;
    gap: 20rpx;
    border-top: 2rpx solid #eee;

    :deep(.u-button) {
      flex: 1;
    }
  }
}
</style> 